package simorg.actions;

import simorg.controller.UserController;
import simorg.domain.User;
import simorg.domain.persistence.UserTable;
import simorg.view.ModelView;
import simorg.view.SessionAttribute;
import simorg.view.WebSessionContext;

public class UserSave extends Action {
	public static String actionName = "save";
	public UserSave() {
		super( actionName);
		this.controllerName = UserController.controllerName;
		
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	

	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		
		User userToSave = UserTable.findById(wc.getDbConnection(), Integer.parseInt(this.getRequestArgs().get(0)));
		
		// Security
		
		// Process post params
		if ( wc.hasReqeustParameter("username")) {
			userToSave.setUsername(wc.getRequestParameter("username"));
		}
		if ( wc.hasReqeustParameter("email")) {
			userToSave.setEmail(wc.getRequestParameter("email"));
		}
		if ( wc.hasReqeustParameter("firstName")) {
			userToSave.setFirstName(wc.getRequestParameter("firstName"));
		}
		if ( wc.hasReqeustParameter("lastName")) {
			userToSave.setLastName(wc.getRequestParameter("lastName"));
		}
		
		
		// Save the user infromation
		UserTable.save(wc.getDbConnection(), userToSave);
		
		// Redirect to user default.
		wc.redirectAdmin((Action)wc.getSessionAttribute(SessionAttribute.DefaultAction));
		return null;
	}
}
